package tableapi.udf;

import bean.SensorReading;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

/**
 * @Description: TODO QQ1667847363
 * @author: xiao kun tai
 * @date:2021/11/9 11:06
 */
public class UDF2_TableFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        String inputPath = "src/main/resources/sensor.txt";

        DataStream<String> inputStream = env.readTextFile(inputPath);

        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //将流转换为表
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id,timestamp as ts,temperature as temp");

        /**
         * 自定义一个表函数，实现对id的拆分，并输出（word，length）
         */
        Split split = new Split("_");


        //需要在环境中注册UDF
        tableEnv.registerFunction("split", split);
        Table resultTable = sensorTable
                .joinLateral("split(id) as(word,length)")
                .select("id,ts,word,length");

        //SQL
        tableEnv.createTemporaryView("sensor", sensorTable);
        Table resultSqlTable = tableEnv.sqlQuery("select id,ts,word,length " +
                "from sensor,lateral table(split(id)) as splitid(word,length) where ts =1547718199 ");


        //打印输出
        tableEnv.toAppendStream(resultTable, Row.class).print("result");
        tableEnv.toAppendStream(resultSqlTable, Row.class).print("sql");
        env.execute();
    }

    /**
     * 实现自定义的TableFunction
     */
    public static class Split extends TableFunction<Tuple2<String, Integer>> {

        //定义分隔符
        private String separator = ",";

        public Split() {

        }

        public Split(String separator) {
            this.separator = separator;
        }

        //必须实现一个eval方法，没有返回值
        public void eval(String str) {
            for(String s :str.split(separator)){
                collect(new Tuple2<>(s,s.length()));
            }
        }
    }
}
